package com.zh.webflux.controller;

import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zh.webflux.common.result.ServiceResult;
import com.zh.webflux.model.UserInfo;
import com.zh.webflux.service.DemoService;
import com.zh.webflux.service.IUserInfoService;

import reactor.core.publisher.Mono;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

@RestController
@RequestMapping("/user")
public class UserInfoController {

	@Resource
	IUserInfoService userInfoService;

	@Resource
	DemoService demoService;

	@GetMapping("/hello")
	public Mono<String> hello() { // 【改】返回类型为Mono<String>
		return Mono.just("Welcome to reactive world ~"); // 【改】使用Mono.just生成响应式数据
	}

	@GetMapping("/getUserInfo.do")
	public Mono<ServiceResult> getUserInfo() {
		List<UserInfo> userInfos = userInfoService.findAll();
		return Mono.just(ServiceResult.success(userInfos)); // 【改】使用Mono.just生成响应式数据
	}

	@GetMapping("/getUserInfo2.do")
	public Mono<ServiceResult> getUserInfo2() {
		List<UserInfo> userInfos = demoService.queryAllInfo();
		return Mono.just(ServiceResult.success(userInfos)); // 【改】使用Mono.just生成响应式数据
	}

	@GetMapping("/getUserInfoAndPage.do")
	public Mono<ServiceResult> getUserInfoAndPage(UserInfo userInfo, @RequestParam(defaultValue = "0") Integer pageNum,
			@RequestParam(defaultValue = "0") Integer pageSize) {
		// 分页
		PageHelper.startPage(pageNum, pageSize);
		// 增加查询条件，criteria.andCondition("xxxx");
		Condition condition = new Condition(UserInfo.class);
		Example.Criteria criteria = condition.createCriteria();
		if (Objects.nonNull(userInfo.getUserId())) {
			criteria.andEqualTo("userId", userInfo.getUserId());
		}

		if (Objects.nonNull(userInfo.getUserName())) {
			criteria.andEqualTo("userName", userInfo.getUserName());
		}
		List<UserInfo> list = userInfoService.findByCondition(condition);
		PageInfo pageInfo = new PageInfo(list);
		return Mono.just(ServiceResult.success(pageInfo)); // 【改】使用Mono.just生成响应式数据
	}

	@GetMapping("/insertUserInfo.do")
	public Mono<ServiceResult> insertUserInfo(UserInfo userInfo) {
		boolean saveUserInfoResult = userInfoService.save(userInfo);
		if (saveUserInfoResult)
			return Mono.just(ServiceResult.error("保存成功"));

		return Mono.just(ServiceResult.success("保存失败")); // 【改】使用Mono.just生成响应式数据
	}

}
